/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ade.prime.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import ade.prime.model.AdeWebOptions;
import ade.prime.model.Lesson;
import ade.prime.model.Lessons;
import android.app.ExpandableListActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;


/**
 * Demonstrates expandable lists backed by a Simple Map-based adapter
 */
public class ExpandableList3 extends ExpandableListActivity {
	
	protected static final String TAG = ExpandableList3.class.getSimpleName() ;
	
	private static final String TITLE = "TITLE" ; //$NON-NLS-1$
	private static final String TIME  = "TIME"  ; //$NON-NLS-1$
	private static final String ROOM  = "ROOM"  ; //$NON-NLS-1$
	private static final String COLOR = "COLOR" ; //$NON-NLS-1$
	private static final String BIG_CHANGE = "BIG_CHANGE" ; //$NON-NLS-1$
	
	public static final String DATE_FORMAT_DAY = "EEEE dd MMMM" ; //$NON-NLS-1$
    
    private ExpandableListAdapter mAdapter;
    
    protected boolean useColor ;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		this.useColor = AdeWebOptions.useAdeWebColors(this) ;

        List<Map<String, String>> groupData = 
        		new ArrayList<Map<String, String>>();
        List<List<Map<String, String>>> childData = 
        		new ArrayList<List<Map<String, String>>>();
        this.buildDailySepartors(groupData, childData, 
        		(Lessons) this.getIntent().getParcelableExtra(
        				BundleExtraNames.EXTRA_SCHEDULE_LESSONS)) ;
//        for (int i = 0; i < 20; i++) {
//            Map<String, String> curGroupMap = new HashMap<String, String>();
//            groupData.add(curGroupMap);
//            curGroupMap.put(NAME, "Group " + i);
//            curGroupMap.put(IS_EVEN, (i % 2 == 0) ? "This group is even" : "This group is odd");
//            
//            List<Map<String, String>> children = new ArrayList<Map<String, String>>();
//            for (int j = 0; j < 15; j++) {
//                Map<String, String> curChildMap = new HashMap<String, String>();
//                children.add(curChildMap);
//                curChildMap.put(NAME, "Child " + j);
//                curChildMap.put(IS_EVEN, (j % 2 == 0) ? "This child is even" : "This child is odd");
//            }
//            childData.add(children);
//        }
        
        // Set up our adapter
        this.mAdapter = new SimpleExpandableListAdapter(
                this,
                groupData,
                R.layout.lesson_list_title_item,
                new String[] { TITLE },
                new int[] { R.id.title },
                childData,
                R.layout.lesson_list_lesson_item,
                new String[] { TITLE, TIME, ROOM },
                new int[] { R.id.title, R.id.time, R.id.room }
                ) {
        	
        	@Override
			public View getChildView(int groupPosition, int childPosition, 
        			boolean isLastChild, View convertView, 
        			ViewGroup parent) {
        		View childView = super.getChildView(groupPosition, childPosition, 
        				isLastChild, convertView, parent) ;
        		this.setupView(childView, this.getChild(groupPosition, childPosition)) ;
        		return childView ;
        	}// getChildView(int, int, boolean, View, ViewGroup)
        	
        	private void setupView(View view, Object child) {
        		@SuppressWarnings("unchecked")
				Map<String, String> childValues = (Map<String, String>) child ;
    			boolean colorItem = ExpandableList3.this.useColor ;

    			TextView timeView  = (TextView) view.findViewById(R.id.time) ;
    			TextView titleView = (TextView) view.findViewById(R.id.title) ;
    			TextView roomView  = (TextView) view.findViewById(R.id.room) ;

    			if (colorItem) {
    				// Set background color
    				String color = childValues.get(COLOR) ;
    				view.setBackgroundColor(Color.parseColor(color)) ;
    				// Change font color
    				titleView.setTextColor(Color.BLACK) ;
    				timeView.setTextColor(Color.BLACK) ;
    				roomView.setTextColor(Color.BLACK) ;
    			}// if

    			// Hide/Show "big change" icon
    			View icon = view.findViewById(R.id.change) ;
    			if (childValues.containsKey(BIG_CHANGE)) {
    				icon.setVisibility(View.VISIBLE) ;
    			} else {
    				icon.setVisibility(View.INVISIBLE) ;
    			}// if
        	}//setupView()
        } ;
        this.setListAdapter(this.mAdapter) ;
    }// onCreate(Bundle)
    
    private void expandAllItems() {
    	ExpandableListView listView = this.getExpandableListView() ;
    	int nGroups = this.mAdapter.getGroupCount() ;
    	for(int pos=0; pos<nGroups; ++pos) {
    		listView.expandGroup(pos) ;
    	}// for
    }// expandAllItems()

	@SuppressWarnings("null")
	private void buildDailySepartors(List<Map<String, String>> groupData,
			List<List<Map<String, String>>> childData, Lessons lessons) {
		final SimpleDateFormat dateFormater = 
				new SimpleDateFormat(DATE_FORMAT_DAY, Locale.FRANCE) ;
		String currentDate = null ;
		List<Map<String, String>> children = null ;
		for(Lesson lesson : lessons) {
			String date = lesson.getTime() ;
			date = date.substring(0, date.indexOf(" ")) ; //$NON-NLS-1$
			if (!date.equals(currentDate)) {
				String formattedDate = dateFormater.format(lesson.getDate()) ;
				// Capitalize first letter
				formattedDate = String.format("%S%s", //$NON-NLS-1$
						formattedDate.substring(0, 1),
						formattedDate.substring(1)) ;
				currentDate = date ;
				Map<String, String> curGroupMap = new HashMap<String, String>() ;
				curGroupMap.put(TITLE, formattedDate) ;
				groupData.add(curGroupMap) ;
				
				children = new ArrayList<Map<String, String>>() ;
				childData.add(children) ;
			}// if
			Map<String, String> curChildMap = new HashMap<String, String>() ;
			children.add(curChildMap) ;
			curChildMap.put(TITLE, getTitle(lesson)) ;
			curChildMap.put(TIME, getTime(lesson)) ;
			curChildMap.put(ROOM, getRoom(lesson)) ;
			curChildMap.put(COLOR, lesson.getColor()) ;
			if (lesson.getChange() == Lesson.BIG_CHANGE) {
				curChildMap.put(BIG_CHANGE, Boolean.TRUE.toString()) ;
			}// if
		}// for
	}// buildDailySepartors(Lessons)
	
	private static String getTitle(Lesson lesson) {
		StringBuilder titleBuilder = new StringBuilder(lesson.getTitle()) ;
		switch (lesson.getType()) {
		case IMPORTANT:
			titleBuilder.append(" (important)") ; //$NON-NLS-1$
			break ;
		case EXAM:
			titleBuilder.append(" (partiel)") ; //$NON-NLS-1$
			break ;
		default:
		}// switch
		return titleBuilder.toString() ;
	}// getTitle(Lesson)
	
	private static String getTime(Lesson lesson) {
		String lessonTime = lesson.getTime() ;
		return lessonTime.substring(lessonTime.indexOf(' ') + 1) ;
	}// getTime(Lesson)
	
	private String getRoom(Lesson lesson) {
		String room = lesson.getRoom() ;
		if ((room == null) || isEmpty(room)) {
			room = this.getResources().getString(R.string.Lesson_room_unknown) ;
		}// if
		return room ;
	}// getRoom(Lesson)
	
	protected static boolean isEmpty(String s) {
		return (s.length() == 0) ;
	}// isEmpty(String)

}
